'use client';

// 添加全局变量声明
declare global {
  interface Window {
    _currentDocumentContent: any;
    _hasUnsavedChanges: boolean; // 新增：用于标记是否有未保存的更改
  }
}

import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { CollaborativeWorkspace } from '@/components/project/collaborative-workspace';
import { CollaborativeEditor } from '@/components/editor/collaborative-editor';
import { Button } from '@/components/ui/button';
import { useAuth } from '@/hooks/use-auth';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { FileText, Users, Clock, History, MessageSquare, ArrowLeft, Save, Share, Trash } from 'lucide-react';
import { toast } from '@/components/ui/use-toast';
import { PermissionLevel } from '@/types/socket';
import { useLocalStorage } from '@/hooks/use-local-storage';

interface DocumentPageProps {}

interface DocumentData {
  id: string;
  title: string;
  content: any;
  version: number;
  createdAt: string;
  updatedAt: string;
  createdBy?: {
    id: string;
    name: string;
  };
}

export default function DocumentPage({ params }: { params: { id: string; documentId: string } }) {
  // 添加参数调试
  console.log("DocumentPage 渲染，原始 params:", params);
  
  const [projectId, setProjectId] = useState<string>('');
  const [documentId, setDocumentId] = useState<string>('');
  
  // 处理 params（可能需要 await）
  useEffect(() => {
    const initParams = async () => {
      try {
        // 在 Next.js 15 中，params 可能是 Promise
        const resolvedParams = await Promise.resolve(params);
        console.log("解析后的 params:", resolvedParams);
        
        setProjectId(resolvedParams.id);
        setDocumentId(resolvedParams.documentId);
      } catch (error) {
        console.error("参数解析错误:", error);
      }
    };
    
    initParams();
  }, [params]);
  
  const router = useRouter();
  const { user } = useAuth();
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [documentData, setDocumentData] = useState<DocumentData | null>(null);
  const [initialContent, setInitialContent] = useState<any>(null);
  const [userPermission, setUserPermission] = useState<PermissionLevel>('viewer');
  
  // 添加本地存储备份功能
  const localStorageKey = `doc_backup_${projectId}_${documentId}`;
  const [localBackup, setLocalBackup, removeLocalBackup] = useLocalStorage<{
    content: any;
    version: number;
    timestamp: number;
    userId: string;
  } | null>(localStorageKey, null);
  
  // 检查本地备份的状态
  const [checkedBackup, setCheckedBackup] = useState(false);
  
  // 加载文档数据
  useEffect(() => {
    console.log("页面参数:", { projectId, documentId });
    
    const fetchDocument = async () => {
      if (!projectId || !documentId) {
        console.log("缺少必要参数，跳过获取文档");
        return;
      }
      
      try {
        setIsLoading(true);
        console.log("开始获取文档数据...", { projectId, documentId });
        
        const url = `/api/projects/${projectId}/document/${documentId}`;
        console.log("请求URL:", url);
        
        const response = await fetch(url);
        console.log("API响应状态:", response.status);
        
        if (!response.ok) {
          const errorText = await response.text();
          console.error("API错误响应:", errorText);
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        console.log("获取到的文档数据:", data);
        
        setDocumentData(data);
        setInitialContent(data.content);
        
        // 设置到全局变量供编辑器使用
        if (typeof window !== 'undefined') {
          window._currentDocumentContent = data.content;
          window._hasUnsavedChanges = false;
        }
        
      } catch (error) {
        console.error("获取文档失败:", error);
        setError(error.message);
      } finally {
        setIsLoading(false);
      }
    };

    fetchDocument();
  }, [projectId, documentId]);
  
  // 检查本地备份 - 只在客户端执行
  useEffect(() => {
    if (typeof window === 'undefined' || checkedBackup || !documentData || !user) return;
    
    // 检查本地备份
    if (localBackup && 
        user.id === localBackup.userId && 
        localBackup.version >= (documentData?.version || 0) &&
        userPermission !== 'viewer') {
      
      // 计算备份时间与服务器版本的时间差
      const backupTime = new Date(localBackup.timestamp);
      const serverTime = new Date(documentData.updatedAt);
      const timeDiff = Math.abs(backupTime.getTime() - serverTime.getTime());
      const diffMinutes = Math.floor(timeDiff / 60000);
      
      let backupIsNewer = localBackup.version > (documentData?.version || 0);
      if (localBackup.version === documentData?.version && diffMinutes > 0) {
        // 如果版本相同但时间有差异，也认为是不同版本
        backupIsNewer = backupTime > serverTime;
      }
      
      if (backupIsNewer) {
        // 提示用户有本地备份可恢复
        const backupTimeStr = backupTime.toLocaleString();
        const serverTimeStr = serverTime.toLocaleString();
        
        // 创建一个持久的提示
        const useBackup = window.confirm(
          `发现本地备份 (${backupTimeStr})，比服务器版本 (${serverTimeStr}) 更新。\n\n` +
          `本地版本: ${localBackup.version}\n` +
          `服务器版本: ${documentData?.version || 0}\n\n` +
          `是否恢复本地备份？选择"取消"将使用服务器版本。`
        );
        
        if (useBackup) {
          setInitialContent(localBackup.content);
          toast({
            title: '已恢复本地备份',
            description: '您的本地编辑内容已恢复，请记得保存以同步到服务器',
            duration: 5000
          });
        } else {
          // 用户选择不使用备份，清除本地备份
          removeLocalBackup();
          toast({
            title: '使用服务器版本',
            description: '已丢弃本地备份，使用服务器最新版本',
            duration: 3000
          });
        }
      } else {
        // 本地备份不比服务器版本新，自动清除
        removeLocalBackup();
      }
    }
    
    setCheckedBackup(true);
  }, [documentData, user, localBackup, userPermission, removeLocalBackup, checkedBackup, toast]);
  
  // 处理API加载失败时的本地备份恢复 - 只在客户端执行
  useEffect(() => {
    if (typeof window === 'undefined' || !isLoading || !localBackup || !user) return;
    
    // 检查本地备份的时间戳，如果过期（超过7天）则不使用
    const now = new Date().getTime();
    const backupTime = new Date(localBackup.timestamp).getTime();
    const daysDiff = Math.floor((now - backupTime) / (1000 * 60 * 60 * 24));
    
    // 如果API加载失败但有本地备份，提示用户使用备份
    if (localBackup.userId === user.id && daysDiff <= 7) {
      const backupDate = new Date(localBackup.timestamp).toLocaleString();
      const useBackup = window.confirm(
        `无法从服务器加载文档，但找到本地备份（${backupDate}）。是否使用本地备份？\n` +
        `注意：本地备份可能不是最新版本，一旦连接恢复，请务必与服务器同步。`
      );
      
      if (useBackup) {
        setDocumentData({
          id: documentId,
          title: '本地备份文档',
          content: localBackup.content,
          version: localBackup.version,
          createdAt: new Date().toISOString(),
          updatedAt: new Date(localBackup.timestamp).toISOString()
        });
        setInitialContent(localBackup.content);
        setUserPermission('editor'); // 假设有编辑权限
        
        toast({
          title: '已加载本地备份',
          description: '服务器连接失败，已加载本地备份。请在网络恢复后保存文档。',
          duration: 5000
        });
        setIsLoading(false);
      }
    }
  }, [isLoading, localBackup, user, documentId, setIsLoading, toast]);
  
  // 页面卸载前自动保存
  useEffect(() => {
    if (typeof window === 'undefined' || !documentData || !user || userPermission === 'viewer') return;
    
    // 创建一个函数来保存当前内容到本地
    const saveBeforeUnload = () => {
      // 使用一个全局变量来获取编辑器当前内容
      if (window._currentDocumentContent && user) {
        // 保存到本地存储
        setLocalBackup({
          content: window._currentDocumentContent,
          version: (documentData?.version || 0) + 1,
          timestamp: Date.now(),
          userId: user.id
        });
      }
    };
    
    // 提示用户未保存的更改
    const warnBeforeUnload = (e: BeforeUnloadEvent) => {
      // 检查是否有未保存的更改
      if (window._hasUnsavedChanges) {
        // 显示标准的"确认离开"对话框
        e.preventDefault();
        const confirmMessage = "您有未保存的更改，确定要离开吗？";
        e.returnValue = confirmMessage;
        return confirmMessage;
      }
    };
    
    // 注册页面卸载事件
    window.addEventListener('beforeunload', saveBeforeUnload);
    window.addEventListener('beforeunload', warnBeforeUnload);
    
    return () => {
      window.removeEventListener('beforeunload', saveBeforeUnload);
      window.removeEventListener('beforeunload', warnBeforeUnload);
    };
  }, [documentData, user, userPermission, setLocalBackup]);
  
  // Next.js路由变化检测 - 防止用户意外离开而丢失更改
  useEffect(() => {
    const handleRouteChange = (url: string) => {
      // 检查是否有未保存的更改
      if (window._hasUnsavedChanges && 
          !url.includes(`/project/${projectId}/document/${documentId}`)) {
        if (!window.confirm('您有未保存的更改，确定要离开吗？')) {
          // 如果用户选择不离开，阻止路由变化
          router.events.emit('routeChangeError');
          // 抛出错误来阻止路由变化
          throw 'routeChange aborted';
        }
      }
    };

    // 监听路由变化开始事件
    router.events?.on('routeChangeStart', handleRouteChange);
    
    return () => {
      // 清理事件监听
      router.events?.off('routeChangeStart', handleRouteChange);
    };
  }, [router, projectId, documentId]);
  
  // 保存文档
  const handleSaveDocument = async (content: any): Promise<void> => {
    try {
      setIsSaving(true);
      console.log("开始保存文档...", { documentId, version: documentData?.version });
      
      // 检查内容有效性
      if (!content || typeof content !== 'object') {
        console.error("保存内容无效:", content);
        throw new Error("文档内容无效");
      }
      
      // 保存到全局变量以便在页面卸载时使用
      if (typeof window !== 'undefined') {
        window._currentDocumentContent = content;
        window._hasUnsavedChanges = true; // 标记有未保存的更改
      }
      
      // 先保存到本地备份
      setLocalBackup({
        content,
        version: (documentData?.version || 0) + 1,
        timestamp: Date.now(),
        userId: user?.id || ''
      });
      console.log("已保存到本地备份");
      
      // 调用API保存文档
      console.log("正在发送API请求保存文档...");
      
      // 详细记录请求内容
      const requestBody = {
        content,
        version: documentData?.version || 1,
        createRevision: true
      };
      
      console.log("API请求地址:", `/api/projects/${projectId}/document/${documentId}`);
      console.log("API请求方法: PUT");
      console.log("API请求内容:", JSON.stringify(requestBody).substring(0, 100) + "...");
      
      // 使用更现代的fetch配置以提高可靠性
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 10000);
      
      try {
        const response = await fetch(`/api/projects/${projectId}/document/${documentId}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache'
          },
          body: JSON.stringify(requestBody),
          signal: controller.signal,
          cache: 'no-store',
          credentials: 'same-origin'
        });
        
        clearTimeout(timeoutId);
        
        console.log("API响应状态:", response.status);
        console.log("API响应头:", Object.fromEntries(response.headers.entries()));
        
        const responseData = await response.json();
        console.log("API响应数据:", responseData);
        
        if (!response.ok) {
          // 处理版本冲突
          if (response.status === 409) {
            toast({
              title: '版本冲突',
              description: '其他用户已更新此文档，请刷新页面获取最新内容',
              variant: 'destructive',
              duration: 7000
            });
          }
          
          throw new Error(responseData.error || responseData.message || '保存文档失败');
        }
        
        // 强制验证文档是否真的更新了
        try {
          console.log("验证文档是否已更新...");
          const verifyResponse = await fetch(`/api/projects/${projectId}/document/${documentId}?t=${Date.now()}`);
          
          if (verifyResponse.ok) {
            const verifyData = await verifyResponse.json();
            console.log("验证响应:", verifyData);
            
            // 检查版本是否已更新
            if (verifyData.version > (documentData?.version || 0)) {
              console.log("验证成功: 文档已成功更新");
              // 确保使用服务器返回的最新数据更新状态
              setDocumentData(verifyData);
            } else {
              console.warn("验证失败: 文档版本未更新");
            }
          }
        } catch (verifyError) {
          console.error("验证文档更新失败:", verifyError);
        }
        
        // 使用API返回的数据更新文档状态
        const updatedDocument = responseData;
        console.log("文档已成功保存，新版本:", updatedDocument.version);
        
        // 更新文档数据
        setDocumentData(updatedDocument);
        
        // 保存成功后清除本地备份
        removeLocalBackup();
        window._hasUnsavedChanges = false; // 保存成功后清除未保存标记
        
        toast({
          title: '保存成功',
          description: '文档已成功保存到服务器',
          duration: 3000
        });
      } catch (fetchError) {
        if (fetchError.name === 'AbortError') {
          console.error('API请求超时');
          toast({
            title: '保存超时',
            description: 'API请求超时，请检查网络连接',
            variant: 'destructive',
            duration: 5000
          });
        } else {
          throw fetchError;
        }
      }
    } catch (error) {
      console.error('保存文档失败:', error);
      toast({
        title: '保存失败',
        description: '文档已保存到本地备份，但未能同步到服务器。请稍后再试。',
        variant: 'destructive',
        duration: 5000
      });
      // 不抛出错误，因为我们已经有本地备份
    } finally {
      setIsSaving(false);
    }
  };
  
  // 检查是否有自动保存的内容
  useEffect(() => {
    if (typeof window === 'undefined' || !documentData || !user) return;
    
    const checkAutoSavedContent = async () => {
      try {
        // 获取最新的自动保存内容
        const response = await fetch(`/api/projects/${projectId}/document/${documentId}`);
        
        if (!response.ok) {
          throw new Error('获取文档失败');
        }
        
        const latestDocument = await response.json();
        
        // 如果服务器上的版本比当前版本更新，提示用户刷新
        if (latestDocument.version > (documentData?.version || 0)) {
          const refreshPage = window.confirm('服务器上有更新的文档版本，是否刷新页面获取最新内容？');
          
          if (refreshPage) {
            window.location.reload();
          }
        }
      } catch (error) {
        console.error('检查自动保存内容失败:', error);
      }
    };
    
    // 页面加载后检查一次
    checkAutoSavedContent();
    
    // 定期检查（每5分钟）
    const checkInterval = setInterval(checkAutoSavedContent, 5 * 60 * 1000);
    
    return () => {
      clearInterval(checkInterval);
    };
  }, [documentData, user, projectId, documentId]);
  
  // 返回项目页面
  const handleBackToProject = () => {
    router.push(`/project/${projectId}`);
  };
  
  // 分享文档
  const handleShareDocument = () => {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href);
    
    toast({
      title: '链接已复制',
      description: '文档链接已复制到剪贴板'
    });
  };
  
  // 删除文档
  const handleDeleteDocument = async () => {
    // 确保在客户端执行
    if (typeof window === 'undefined') return;
    
    if (!window.confirm('确定要删除此文档吗？此操作无法撤销。')) {
      return;
    }
    
    try {
      // 调用API删除文档
      const response = await fetch(`/api/projects/${projectId}/document/${documentId}`, {
        method: 'DELETE'
      });
      
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || '删除文档失败');
      }
      
      toast({
        title: '删除成功',
        description: '文档已成功删除'
      });
      
      // 返回项目页面
      router.push(`/project/${projectId}`);
    } catch (error) {
      console.error('删除文档失败:', error);
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '无法删除文档，请重试',
        variant: 'destructive'
      });
    }
  };
  
  if (isLoading || !documentData) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary"></div>
      </div>
    );
  }
  
  return (
    <div className="flex flex-col h-screen">
      {/* 顶部工具栏 */}
      <header className="border-b p-4 bg-background">
        <div className="flex justify-between items-center">
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="icon" onClick={handleBackToProject}>
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <h1 className="text-xl font-semibold truncate">{documentData.title}</h1>
          </div>
          
          <div className="flex items-center gap-2">
            {/* 添加明确的保存按钮用于调试 */}
            <Button 
              variant="default" 
              size="sm" 
              onClick={() => {
                console.log("手动保存按钮点击");
                try {
                  // 尝试获取当前编辑器内容
                  const content = window._currentDocumentContent || {};
                  console.log("获取到编辑器内容:", content);
                  
                  // 确保内容不为空
                  if (!content || Object.keys(content).length === 0) {
                    console.warn("编辑器内容为空，尝试获取一个默认内容");
                    // 创建一个最小的文档内容
                    const defaultContent = {
                      type: "doc",
                      content: [
                        {
                          type: "paragraph",
                          content: [
                            {
                              type: "text",
                              text: "这是一个测试段落"
                            }
                          ]
                        }
                      ]
                    };
                    console.log("使用默认内容:", defaultContent);
                    handleSaveDocument(defaultContent);
                  } else {
                    // 调用保存函数
                    console.log("调用handleSaveDocument");
                    handleSaveDocument(content);
                  }
                } catch (error) {
                  console.error("保存按钮点击处理出错:", error);
                  alert("保存出错，请查看控制台");
                }
              }}
            >
              <Save className="h-4 w-4 mr-2" />
              保存文档
            </Button>
            
            {/* 添加直接测试API的按钮 */}
            <Button 
              variant="destructive" 
              size="sm" 
              onClick={async () => {
                console.log("测试API按钮点击");
                try {
                  // 创建一个简单的测试内容
                  const testContent = {
                    type: "doc",
                    content: [
                      {
                        type: "paragraph",
                        content: [
                          {
                            type: "text",
                            text: "API测试 " + new Date().toISOString()
                          }
                        ]
                      }
                    ]
                  };
                  
                  console.log("直接调用API，绕过handleSaveDocument函数");
                  console.log("发送内容:", testContent);
                  
                  // 直接调用API，绕过handleSaveDocument函数
                  const response = await fetch(`/api/projects/${projectId}/document/${documentId}`, {
                    method: 'PUT',
                    headers: {
                      'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                      content: testContent,
                      version: documentData?.version || 1,
                      createRevision: true
                    })
                  });
                  
                  console.log("API响应状态:", response.status);
                  const responseData = await response.json();
                  console.log("API响应数据:", responseData);
                  
                  alert(`API测试结果: ${response.status}, 详见控制台`);
                } catch (error) {
                  console.error("API测试出错:", error);
                  alert(`API测试出错: ${error.message}`);
                }
              }}
            >
              测试API
            </Button>
            
            {/* 添加API连接检测按钮 */}
            <Button 
              variant="secondary" 
              size="sm" 
              onClick={async () => {
                try {
                  console.log("检查服务器连接...");
                  
                  // 1. 测试文档API可用性
                  console.log("1. 测试文档API...");
                  const docResponse = await fetch(`/api/projects/${projectId}/document/${documentId}`, { 
                    method: 'GET'
                  });
                  console.log(`文档API状态: ${docResponse.status}`);
                  
                  // 2. 测试健康检查API
                  console.log("2. 测试健康检查API...");
                  const healthResponse = await fetch('/api/health');
                  console.log(`健康检查API状态: ${healthResponse.status}`);
                  
                  // 3. 测试数据库连接
                  console.log("3. 测试数据库连接...");
                  const dbResponse = await fetch('/api/system/db-status');
                  console.log(`数据库状态API: ${dbResponse.status}`);
                  
                  // 如果所有测试都通过，显示成功消息
                  if (docResponse.ok && healthResponse.ok) {
                    alert("所有API连接正常！详见控制台日志");
                  } else {
                    alert("部分API连接异常，详见控制台日志");
                  }
                } catch (error) {
                  console.error("API连接检查失败:", error);
                  alert(`API连接检查失败: ${error.message}`);
                }
              }}
            >
              检查API连接
            </Button>
            
            {/* 添加直接数据库测试按钮 */}
            <Button 
              variant="outline" 
              size="sm" 
              onClick={async () => {
                try {
                  console.log("直接测试数据库...");
                  
                  // 创建一个直接调用Prisma的API
                  const testApiUrl = '/api/system/db-status?action=update_document';
                  
                  // 创建测试内容
                  const testData = {
                    documentId: documentId,
                    projectId: projectId,
                    title: "数据库测试 " + new Date().toISOString(),
                    content: {
                      type: "doc",
                      content: [{ type: "paragraph", content: [{ type: "text", text: "数据库直接测试" }] }]
                    }
                  };
                  
                  console.log("发送测试数据:", testData);
                  
                  // 发送请求
                  const response = await fetch(testApiUrl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(testData)
                  });
                  
                  console.log("数据库测试响应状态:", response.status);
                  const responseData = await response.json();
                  console.log("数据库测试结果:", responseData);
                  
                  alert(`数据库测试结果: ${response.ok ? '成功' : '失败'}, 详见控制台`);
                } catch (error) {
                  console.error("数据库测试失败:", error);
                  alert(`数据库测试失败: ${error.message}`);
                }
              }}
            >
              测试数据库
            </Button>
            
            <Button variant="outline" size="sm" onClick={handleShareDocument}>
              <Share className="h-4 w-4 mr-2" />
              分享
            </Button>
            
            <Button variant="outline" size="sm" onClick={handleDeleteDocument} className="text-destructive">
              <Trash className="h-4 w-4 mr-2" />
              删除
            </Button>
            
            <Button 
              variant="outline" 
              size="sm" 
              onClick={async () => {
                console.log("手动获取文档数据...");
                try {
                  const response = await fetch(`/api/projects/${projectId}/document/${documentId}`);
                  console.log("手动获取响应状态:", response.status);
                  const data = await response.json();
                  console.log("手动获取的数据:", data);
                  
                  setDocumentData(data);
                  setInitialContent(data.content);
                  
                  alert("数据已手动加载，请查看控制台");
                } catch (error) {
                  console.error("手动获取失败:", error);
                  alert("手动获取失败: " + error.message);
                }
              }}
            >
              手动加载数据
            </Button>
          
            // 在渲染编辑器的地方添加调试信息
            console.log("传递给编辑器的数据:", { 
              initialContent, 
              documentData,
              projectId,
              documentId 
            });

            // 确保 initialContent 正确设置
            useEffect(() => {
              if (documentData && documentData.content) {
                console.log("设置 initialContent:", documentData.content)
                setInitialContent(documentData.content);
              }
            }, [documentData]);

          
            // 在渲染编辑器的地方添加调试信息
            console.log("传递给编辑器的数据:", { 
              initialContent, 
              documentData,
              projectId,
              documentId 
            });

            // 确保 initialContent 正确设置
            useEffect(() => {
              if (documentData && documentData.content) {
                console.log("设置 initialContent:", documentData.content);
                setInitialContent(documentData.content);
              }
            }, [documentData]);
          
            // 在渲染编辑器的地方添加调试信息
            console.log("传递给编辑器的数据:", { 
              initialContent, 
              documentData,
              projectId,
              documentId 
            });

            // 确保 initialContent 正确设置
            useEffect(() => {
              if (documentData && documentData.content) {
                console.log("设置 initialContent:", documentData.content);
                setInitialContent(documentData.content);
              }
            }, [documentData]);
          
